// import WsRequest from '../../utils/ws-request/index';
import ApiConfig from "@/api/request/api-config.js";
import { getToken } from "@/utils/auth";
import api from "@/api/request/index.js";
import { Message } from "element-ui";

const state = () => ({
	socketState: "close", //open, close
	wsRequest: null,
	heartInterval: null, //心跳
	chatDialogVisible: false,
	socketUrl: `${ApiConfig.socketUrl}/chat/ws?token=${getToken()}`,
	unreadNum: null,
	contactList: [], //联系人
	currentContactDetail: {
		userId: null,
		createTime: null,
		username: null,
	}, //当前沟通中联系人
	currentContactHistory: [], //当前聊天历史数据
	pageInfo: {
		pageIndex: 1,
		pageSize: 12,
		total: 0,
	},
});

const mutations = {
	SET_SCOKET_URL(state, socketUrl){
		state.socketUrl = socketUrl;
	},
	SET_WS_REQUEST(state, wsRequest){
		state.wsRequest = wsRequest;
	},
	SET_SCOKET_STATE(state, socketState) {
		state.socketState = socketState;
	},
	// 初始化当前页数
	SET_PAGE_INFO_INIT(state) {
		state.pageInfo = {
			pageIndex: 1,
			pageSize: 12,
			total: 0,
		};
	},
	SET_PAGEINFO_PAGEINDEX(state, pageIndex) {
		state.pageInfo.pageIndex = pageIndex;
	},
	SET_PAGEINFO_TOTAL(state, total) {
		state.pageInfo.total = total;
	},
	SET_HEART_INTERVAL(state, setInterval){
		state.heartInterval = setInterval;
	},
	SET_SCOKET_INIT(state){
		state.heartInterval = null;
		state.unreadNum = null;
		state.contactList = [];
		state.currentContactDetail = {
			userId: null,
			createTime: null,
			username: null
		};
		state.currentContactHistory = [];
		console.log("SET_SCOKET_INIT");
	},
	SET_CHAT_DIALOG_VISIBLE(state, chatDialogVisible){
		state.chatDialogVisible = chatDialogVisible;
		console.log("state.chatDialogVisible", state);
	},
	SET_CONTACTLIST(state, contactList){
		state.contactList = contactList;
		console.log("SET_CONTACTLIST", contactList);
	},
	SET_CURRENT_CONTACTHISTORY(state, currentContactHistory) {
		state.currentContactHistory = currentContactHistory;
	},
	SET_CURRENTCONTACTDETAIL(state, currentContactDetail){
		state.currentContactDetail = currentContactDetail;
	}
};

const actions = {
	scoketOpen({ commit, state, dispatch }, token) {
		if(process.client){
			const socketUrl = `${ApiConfig.socketUrl}/chat/ws?token=${token}`;
			commit("SET_SCOKET_URL", socketUrl);
			if (state.wsRequest != null) {
				console.log("重新初始化");
				state.wsRequest.close();
			}
			const wsRequest = new WebSocket(
				`${ApiConfig.socketUrl}/chat/ws?token=${getToken()}`
			);

			wsRequest.onopen = function () {
				console.log("开启");
				commit("SET_SCOKET_STATE", "open");
				dispatch('scoketInit');
			};

			wsRequest.onclose = function () {
				console.log("关闭");
				commit("SET_SCOKET_STATE", "close");
				commit("SET_WS_REQUEST", null);
			};
			wsRequest.onmessage = function (msg) {
				let realContent = {};
				console.log(msg, "消息接收");
				if (msg.data) {
					const newMsg = JSON.parse(msg.data);
					if (newMsg.content) {
						if (
							typeof newMsg.content == "string" &&
							newMsg.content.indexOf("errMsg") > -1
						) {
							const allContent = `${
								newMsg.content.split(",errMsg")[0]
							}`;
							const content = allContent.split("msg:")[1];
							realContent = JSON.parse(content);
						} else {
							realContent = newMsg;
						}
						if (realContent && realContent.msgType == "read") {
							state.contactList.map((element) => {
								if (element.userId == realContent.id) {
									element.unread = realContent.unread;
								}
							});
							return true;
						}
						if (realContent && realContent.msgType == "tip") {
							Message.closeAll();
							Message({
								message: newMsg.content,
								type: "warning",
							});
						}
						if (Object.keys(realContent || {}).includes("unreadNum")) {
							state.contactList.map((element) => {
								if (element.userId == realContent.fromUserId) {
									element.unreadNum =
										(element.unreadNum || 0) +
										(realContent.unreadNum || 0);
								}
							});
							if (state.currentContactDetail.userId) {
								commit("SET_PAGE_INFO_INIT");
								dispatch(
									"setCurrentContactDetail",
									state.currentContactDetail
								);
							}
						} else {
							commit("SET_PAGE_INFO_INIT");
							dispatch(
								"setCurrentContactDetail",
								state.currentContactDetail
							);
						}
					} else {
						// 已读
						if (newMsg && newMsg.msgType == "read") {
							state.contactList.map((element) => {
								if (element.userId == newMsg.id) {
									element.unreadNum = realContent.unread
										? element.unreadNum
										: 0;
								}
							});
							return true;
						} else if (newMsg && newMsg.msgType == "unreadNum") {
							state.unreadNum = newMsg.unreadNum || 0;
						}
					}
				}
			};
			wsRequest.onerror = function (msg) {
				console.log(msg, "报错");
			};
			commit("SET_WS_REQUEST", wsRequest);
			if (state.wsRequest) {
				commit("SET_HEART_INTERVAL", setInterval(() => {
					if (state.wsRequest) {
						state.wsRequest.send(
							JSON.stringify({ msgType: "heartbeat" })
						);
					} else {
						clearInterval(state.heartInterval);
					}
				}, 3600000));
			}
		}
	},
	scoketClose({ state }) {
		console.log("scoketClose");
		state.wsRequest && state.wsRequest.onclose();
	},
	scoketInit({commit}) {
		commit("SET_SCOKET_INIT");
	},
	scoketSend({ state, dispatch }, params) {
		// 文本text、图片image、语音voice、视频video、心跳heartbeat、已读read
		if (state.socketState != "open") {
			dispatch("scoketOpen", getToken());
			return true;
		}
		try {
			state.wsRequest.send(JSON.stringify(params), function (event) {
				event.preventDefault();
			});
		} catch (e) {
			dispatch("scoketOpen", getToken());
		}
	},
	// 设置当前沟通联系人
	setCurrentContactDetail({ state, dispatch, commit }, detail) {
		return new Promise((resolve) => {
		});
	},
	// 联系人
	getContactList(
		{ dispatch, commit },
		userInfo = { userId: 0, username: "", cnCompanyName: "", logo: "" }
	) {
		console.log(userInfo, "?userInfo-chat");
		return new Promise((resolve) => {
		});
	},
	// 设置已读
	setRead({ state, dispatch }, userId) {
		return new Promise((resolve) => {
			console.log("setRead", userId, state);
		});
	},
	// 获取历史数据
	getContactHistory({ state, commit }, detail) {
		return new Promise((resolve) => {
		});
	},
};

export default {
	namespaced: true,
	state,
	mutations,
	actions,
};
